package com.pmcc.utils.wechat;

import com.alibaba.fastjson.JSON;
import com.pmcc.platform.user.entity.UserInfo;
import com.pmcc.platform.user.repository.UserInfoRepository;
import com.pmcc.utils.ApiResultBean;
import com.pmcc.utils.StringUtil;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.util.List;

/**
 * @program: basePlatform
 * @description: 微信支付基础配置类
 * @author: Mr.Xue
 * @create: 2020-03-25 15:09
 **/
@Transactional
public class WechatMiniConfig {

    @Autowired
    UserInfoRepository userInfoRepository;


    public static String ID = "wxfeeb7daf89519654";//用于手机端微信授权
    public static String SECRET = "b1d7c183319dfb34195b47d4068317e1";//用于手机端微信授权
    public static String APP_URL = "https://api.weixin.qq.com/sns/";//用于手机端微信授权

            //        导购端
    public static String MINI_APP_ID = "wx794dfaca573c5ed8";//小程序appId
    public static String MINI_APP_SECRET = "ec11163e88dbd6d683c71d340f309e85";//AppSecret(小程序密钥)

            //业务员

    public static String SALESAMAN_MINI_APP_ID = "wx5577a819da62bd9c";//小程序appId
    public static String SALESAMAN_MINI_APP_SECRET = "0f137a25c2bc5422f1211a1644622c7f";//AppSecret(小程序密钥)

    public static DefaultHttpClient httpclient;

    private static final Logger logger = LoggerFactory.getLogger(WechatMiniConfig.class);

    static {
        httpclient = new DefaultHttpClient();
        httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient);
    }

    /**
     * 生成微信预支付订单
     *
     * @param url
     * @param xmlParam
     * @return
     */
    public static Object getPayNum(String url, String xmlParam, String appKey) {
        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
        UnifiedOrderResult unifiedOrderResult = new UnifiedOrderResult();
        try {
            httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
            HttpResponse response = httpclient.execute(httpost);
            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            //转换成实体，然后签名，签名以后进行比较
            unifiedOrderResult = (UnifiedOrderResult) WechatUtil.fromXml(jsonStr, UnifiedOrderResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unifiedOrderResult;
    }

    /**
     * 服务商获取预支付订单
     * @param url     统一下单地址
     * @param xmlParam 签名参数
     * @param appKey 服务商的MchKey
     * @param miniProgramAppId 小程序AppId
     * @return
     */
    public static Object getPayNum(String url, String xmlParam, String appKey,String miniProgramAppId) {
        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
        UnifiedOrderResult unifiedOrderResult = new UnifiedOrderResult();
        try {
            httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
            HttpResponse response = httpclient.execute(httpost);
            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            //转换成实体，然后签名，签名以后进行比较
            unifiedOrderResult = (UnifiedOrderResult) WechatUtil.fromXml(jsonStr, UnifiedOrderResult.class);
            //重新签名
            unifiedOrderResult.setAppid(miniProgramAppId);
            String newSign = WechatUtil.paySign(unifiedOrderResult, appKey);
            unifiedOrderResult.setSign(newSign);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unifiedOrderResult;
    }


    /**
     * 商户号付款到零钱
     * @param url
     * @param xmlParam
     * @param certPath
     * @return
     */
   /* public static Object transfersMoney(String url, String xmlParam, String certPath) {
        KeyStore keyStore = null;//证书
        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
        TransfersOrderResult transfersOrderResult = new TransfersOrderResult();
        try {
            //获取证书
            keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream inputStream = new FileInputStream(new File(certPath));
            keyStore.load(inputStream, SUB_MCH_ID.toCharArray());
            inputStream.close();
            SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, SUB_MCH_ID.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();
            httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
            HttpResponse response = httpclient.execute(httpost);
            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            logger.info("--------------------------------------------" + jsonStr);
            transfersOrderResult = (TransfersOrderResult) WechatUtil.fromXml(jsonStr, TransfersOrderResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return transfersOrderResult;
    }*/

    /**
     * 用户取消订单，退款
     *
     * @param xmlParam
     * @param certPath
     * @return
     */
    /*public static Object orderRefund(String xmlParam, String certPath) {
        KeyStore keyStore = null;//证书
        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpPost httpost = HttpClientConnectionManager.getPostMethod(REFUND_URL);
        PayResult payResult = new PayResult();
        try {
            //获取证书
            keyStore = KeyStore.getInstance("PKCS12");
            FileInputStream inputStream = new FileInputStream(new File(certPath));
            keyStore.load(inputStream, MCH_ID.toCharArray());
            inputStream.close();
            SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, MCH_ID.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1"},
                    null,
                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();
            httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
            HttpResponse response = httpclient.execute(httpost);
            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            logger.info("--------------------------------------------" + jsonStr);
            payResult = (PayResult) WechatUtil.fromXml(jsonStr, PayResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return payResult;
    }*/

    /**
     * 获取AccessToken
     * @return 返回拿到的access_token及有效期
     */
    public static String getAccessToken() throws IOException {
        String token = new String();
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WechatMiniConfig.MINI_APP_ID+"&secret="+ WechatMiniConfig.MINI_APP_SECRET+"";
        //String url = ACCESS_TOKEN_URL.replace("APPID",WechatMiniConfig.MINI_APP_ID).replace("APPSECRET",WechatMiniConfig.MINI_APP_SECRET);
        JSONObject jsonObject = doGetStr(url);//使用刚刚写的doGet方法接收结果
        if(jsonObject!=null){ //如果返回不为空，将返回结果封装进AccessToken实体类
            //token.setAccessToken(jsonObject.getString("access_token"));//取出access_token
            //token.setExpiresIn(jsonObject.getInt("expires_in"));//取出access_token的有效期
            token = jsonObject.getString("access_token");
        }
        return token;
    }


    /**
     * 编写Get请求的方法。但没有参数传递的时候，可以使用Get请求
     *
     * @param url 需要请求的URL
     * @return 将请求URL后返回的数据，转为JSON格式，并return
     */
    public static JSONObject doGetStr(String url) throws ClientProtocolException, IOException {
        DefaultHttpClient client = new DefaultHttpClient();//获取DefaultHttpClient请求
        HttpGet httpGet = new HttpGet(url);//HttpGet将使用Get方式发送请求URL
        JSONObject jsonObject = null;
        HttpResponse response = client.execute(httpGet);//使用HttpResponse接收client执行httpGet的结果
        HttpEntity entity = response.getEntity();//从response中获取结果，类型为HttpEntity
        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");//HttpEntity转为字符串类型
            jsonObject = JSONObject.fromObject(result);//字符串类型转为JSON类型
        }
        return jsonObject;
    }


    public static String getAccessToken1() throws IOException {
        String token = new String();
        String appid="wx794dfaca573c5ed8";
        String secret="ec11163e88dbd6d683c71d340f309e85";
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ "wx08b32617cfbffc24"+"&secret="+"cd9cb83d6295a99c19f1dde684eff301"+"";
        //String url = ACCESS_TOKEN_URL.replace("APPID",WechatMiniConfig.MINI_APP_ID).replace("APPSECRET",WechatMiniConfig.MINI_APP_SECRET);
        JSONObject jsonObject = doGetStr(url);//使用刚刚写的doGet方法接收结果
        if(jsonObject!=null){ //如果返回不为空，将返回结果封装进AccessToken实体类
            //token.setAccessToken(jsonObject.getString("access_token"));//取出access_token
            //token.setExpiresIn(jsonObject.getInt("expires_in"));//取出access_token的有效期
            token = jsonObject.getString("access_token");
        }
        return token;
    }



}
